c# 4.0 - best way to refactor a block of "If (something is Type) {}" statements?

Posted by Andrew Johns on Stack Overflow See other posts from Stack Overflow or by Andrew Johns
Published on 2010-05-06T11:40:45Z Indexed on 2010/05/06 11:48 UTC
Read the original article Hit count: 192

Filed under:
|
|

I've got some code that looks like this,

public void ResetControls(Control controlOnPage)
{
    if (controlOnPage is TextBox)
    {
        ResetTextBoxControl(controlOnPage);
    }

    if (controlOnPage is MediaPicker)
    {
        ((MediaPicker)controlOnPage).Media = null;
    }

    if (controlOnPage is RelatedContentPicker)
    {
        ((RelatedContentPicker)controlOnPage).RelatedContentCollection = null;
    }
    ...
    ...

    foreach (Control child in controlOnPage.Controls)
    {
        ResetControls(child);
    }
}

The idea behind it is that I can pass a page to the method and it'll recursively reset all the controls on it to their default states - in the case of MediaPicker and RelatedContentPicker, these are user controls that I've created.

FXCop warns me "Do Not Cast Unnecessarily" for this code - but I'm unsure how to rewrite it to make it better. Any ideas?

© Stack Overflow or respective owner

Related posts about c#4.0

Related posts about refactor